from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import sessionmaker

from src.core.config import settings
from src.models.base import Base


# 初始化数据库：创建所有表（如果表不存在）

def create_tables():
    Base.metadata.create_all(bind=sync_engine)

# ------------------------------
# 同步引擎（用于数据库迁移等操作）
# ------------------------------
sync_engine = create_engine(
    settings.db_url_sync,
    echo=False,  # 生产环境关闭SQL日志
    pool_size=10,
    max_overflow=20,
    pool_recycle=3600,  # MySQL默认wait_timeout为8小时，这里设置1小时自动回收连接
    pool_pre_ping=True  # 连接前检查可用性，避免失效连接
)

# 同步会话工厂
SyncSessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=sync_engine
)

# ------------------------------
# 异步引擎（用于FastAPI主程序）
# ------------------------------
async_engine = create_async_engine(
    settings.db_url_async,
    echo=False,
    pool_size=10,
    max_overflow=20,
    pool_recycle=3600,
    pool_pre_ping=True
)

# 异步会话工厂
AsyncSessionLocal = async_sessionmaker(
    bind = async_engine,
    class_=AsyncSession,
    autocommit=False,
    autoflush=False
)


# ------------------------------
# 依赖注入函数
# ------------------------------
def get_sync_db():
    """同步数据库会话依赖（用于迁移）"""
    db = SyncSessionLocal()
    try:
        yield db
    finally:
        db.close()


async def get_async_db():
    """异步数据库会话依赖（用于FastAPI接口）"""
    async with AsyncSessionLocal() as db:
        yield db
        await db.commit()



